var cluster = require('cluster');
var http = require('http');
var numCPUs = require('os').cpus().length;
var workers = {};
var requests = 0;

if (cluster.isMaster) {
	for (var i = 0; i < numCPUs; i++) {
		workers[i] = cluster.fork();

		(function(i) {
			// 监听来自工人的消息
			workers[i].on('message', function(message) {
				if (message.cmd == 'incrementRequestTotal') {
					requests++;
					console.log("requests: " + requests + " pid: " + process.pid);
					for (var j = 0; j < numCPUs; j++) {
						// 将新的请求总数发送给所有工人
						workers[j].send({
							cmd: 'updateOfRequestTotal',
							requests: requests
						});
					}
				}
			});			
		})(i);			// 用闭包保留工人的值
	}

	cluster.on('exit', function(worker, code, signal) {
		console.log('Worker ' + worker.process.pid + ' died.');
	});
} else {
	// 监听来自主进程的消息
	process.on('message', function(message) {
		if (message.cmd == 'updateOfRequestTotal') {
			requests = message.requests;
		}
	});
	http.createServer(function(req, res) {
		console.log(req.url);
		res.writeHead(200);
		res.end('Worker in process ' + process.pid
			+ ' says cluster has responded to ' + requests
			+ ' requests.');
		// 通过主进程增加请求总数
		process.send({cmd:'incrementRequestTotal'});
	}).listen(8000);
}